package com.yangyang.androidconnect.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IpUtil {

    /**
     * 获取首选IPv4地址
     */
    public static String getLocalIPv4IP() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();
                // 接口级别过滤（已包含回环检查）&& ni.supportsMulticast()
                if (!ni.isLoopback() && ni.isUp() && (isCellularInterface(ni) || ni.supportsMulticast()) && !ni.isVirtual()) {
                    Enumeration<InetAddress> addresses = ni.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = addresses.nextElement();
                        // 地址级别过滤（去掉冗余的loopback检查）
                        if (addr instanceof Inet4Address && !addr.isLinkLocalAddress()) {
                            return addr.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getFallbackIP();
    }

    public static boolean isCellularInterface(NetworkInterface ni) {
        String name = ni.getName().toLowerCase();

        // 常见的蜂窝网络接口名称模式
        return name.contains("rmnet") ||    // Android 常见蜂窝接口
                name.contains("pdp") ||      // PDP (Packet Data Protocol)
                name.contains("wwan") ||     // Wireless WAN
                name.contains("cellular") || // 蜂窝网络
                name.contains("umts") ||     // UMTS 网络
                name.contains("gsm") ||      // GSM 网络
                name.contains("lte") ||      // LTE 网络
                name.contains("nr") ||       // 5G NR 网络
                name.startsWith("ccmni") ||  // 中国移动等定制接口
                name.startsWith("r_rmnet");  // 某些设备的蜂窝接口
    }

    // 提供回退方案
    private static String getFallbackIP() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
            return "127.0.0.1";
        }
    }
}
